const http = require('http')
const querystring = require('querystring')

module.exports = function proxy({host='localhost',port=80,proxyPort=4040})
{
    const server = http.createServer((req,res)=>{
        res.setHeader('Access-Control-Allow-Credentials', 'true')
        res.setHeader('Access-Control-Allow-Origin', '*')
        res.setHeader('Access-Control-Allow-Methods', 'POST,GET,OPTIONS,PUT,DELETE')
        res.setHeader('Access-Control-Allow-Headers', 'authorization,x-amz-date,origin,x-requested-with,access-control-request-headers,content-type,access-control-request-method,accept,x-amz-credential')
        switch(req.method){
            case 'GET':
                _proxyGet(req,res)
                break
            case 'POST':
                _proxyPost(req,res)
                break
            case 'OPTIONS':
                // 这一部分解决Preflight请求响应问题
                res.setHeader('Access-Control-Allow-Headers', req.headers['access-control-request-headers']);
                res.setHeader('Origin', 'http://localhost:9528');
                // if(req.headers['Authorization']) {
                //   res.setHeader('Authorization', req.headers['Authorization']);
                // }
                res.write('ok')
                res.end()
                break
            default:
                res.write('method: ' + req.method)
                res.end()
                break
        }

    }).listen(proxyPort,()=>{
        console.log(`代理监听端口号: ${proxyPort}`)
    })

    function _proxyGet(req,res){
        req.headers.Origin = 'http://localhost:9528';
        http.get({
            hostname:host,
            port,
            path:req.url,
            headers: req.headers
        },proxyRes=>{
            proxyRes.headers['access-control-allow-origin'] = null
            pipeRes(proxyRes,res)
        })
    }
    function pipeRes(proxyRes,res){
        res.writeHead(proxyRes.statusCode,proxyRes.headers);
        proxyRes.pipe(res)
    }
    function _proxyPost(req,res) {
        let body  = '';
        req.setEncoding('utf8')
        req.addListener('data',chunk=>{
            body = chunk
        }).addListener('end',()=>{
            delete req.headers.referer
            let json = JSON.parse(body)
            console.log('*************************')
            console.log(req.headers);
            req.headers.origin = 'http://localhost:9528';
            if (req.headers['content-type'] == 'application/json') {
                body = ''
                for (key in json) {
                  body += encodeURI(key) + '=' + encodeURI(json[key]) + '&'
                }
                body = body.substring(0, body.length-1)
                req.headers['Content-Type'] = 'application/json'
                req.headers['Content-Length'] = JSON.stringify(json).length
            }

            // 输出控制台
            console.log('*************************')
            console.log('请求地址为: ' + host + req.url)
            console.log('请求头信息: ' + JSON.stringify(req.headers))
            console.log('请求类型为: ' + req.method)
            console.log('请求数据为: ' + JSON.stringify(json))
            console.log('数据长度为: ' + body.length)
            console.log('*************************')

            let request = http.request({
                method:req.method,
                host,
                port,
                path:req.url,
                headers:req.headers,
            }, proxyRes => {
                proxyRes.headers['access-control-allow-origin'] = null
                pipeRes(proxyRes, res)
                console.log('响应状态码: ' + proxyRes.statusCode);
                console.log('响应头信息: ' + JSON.stringify(proxyRes.headers));
            })

            request.write(JSON.stringify(json))
            request.end()
        })
    }
}
